package com.qinge.blog.service.impl;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.qinge.blog.service.CaptchaService;
import com.qinge.blog.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;


import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author QDW
 * @date 2022/5/4 19:19
 * @description CaptchaService实现类
 **/
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private DefaultKaptcha producer;

    // 从SpringBoot的配置文件中取出过期时间
    @Value("${server.servlet.session.timeout}")
    private Integer timeout;

    /**
     * @author QDW
     * @date 2022/5/4 19:22
     * @description UUID为key, 验证码为Value放在Redis中
     * @param captcha
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    @Override
    public Map<String, Object> createUUID(String captcha) {
        // 生成一个token
        String key = UUIDUtil.getUUID32();

        // 生成验证码对应的token  以token为key  验证码为value存在redis中
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, captcha);

        // 设置验证码过期时间
        redisTemplate.expire(key, timeout, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", key);
        map.put("expire", timeout);

        return map;
    }

    /**
     * @author QDW
     * @date 2022/5/4 19:22
     * @description 生成captcha验证码
     * @param
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    @Override
    public Map<String, Object> captchaCreator() throws IOException {
        // 生成文字验证码
        String text = producer.createText();

        // 生成文字对应的图片验证码
        BufferedImage image = producer.createImage(text);

        // 将图片写出
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        // 对写出的字节数组进行Base64编码 ==> 用于传递8比特字节码
        BASE64Encoder encoder = new BASE64Encoder();

        // 生成UUID
        Map<String, Object> map = createUUID(text);
        map.put("img", encoder.encode(outputStream.toByteArray()).replaceAll("\r|\n", ""));

        return map;
    }

    /**
     * @author QDW
     * @date 2022/5/4 19:22
     * @description 验证输入的验证码是否正确
     * @param UUID
     * @param inputCode
     * @return java.lang.String
     **/
    @Override
    public boolean versifyCaptcha(String UUID, String inputCode) {
        // 根据前端传回的UUID在redis中找对应的value
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();

        if (redisTemplate.hasKey(UUID)) {
            // 验证通过, 删除对应的key
            if (valueOperations.get(UUID).equals(inputCode)) {
                redisTemplate.delete(UUID);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


}
